import type { Song } from './api';

const KEY_USER = 'user';
const KEY_FAV = 'favorites';
const KEY_HISTORY = 'history';
const KEY_PLAYLIST = 'playlist';

export const getUser = () => wx.getStorageSync(KEY_USER) || null;
export const setUser = (user: any) => wx.setStorageSync(KEY_USER, user);

export const getFavorites = (): Song[] => wx.getStorageSync(KEY_FAV) || [];
export const setFavorites = (list: Song[]) => wx.setStorageSync(KEY_FAV, list);
export const toggleFavorite = (song: Song) => {
  const list: Song[] = getFavorites();
  const exists = list.find(s => s.id === song.id);
  const next = exists ? list.filter(s => s.id !== song.id) : [song, ...list];
  setFavorites(next);
  return next;
};

export const getHistory = (): Song[] => wx.getStorageSync(KEY_HISTORY) || [];
export const addHistory = (song: Song) => {
  const list: Song[] = getHistory().filter(s => s.id !== song.id);
  list.unshift(song);
  setHistory(list.slice(0, 50));
};
export const setHistory = (list: Song[]) => wx.setStorageSync(KEY_HISTORY, list);

export const getPlaylist = (): Song[] => wx.getStorageSync(KEY_PLAYLIST) || [];
export const setPlaylist = (list: Song[]) => wx.setStorageSync(KEY_PLAYLIST, list);